<script>
	import Vue from "vue";
	import {
		MQTT_OPTIONS,
		MQTT_IP
	} from './utils/mqttConfig.js'
	import {
		getCache,
		setCache,
		apiUrl
	} from "@/utils/cache.js";
	// #ifdef APP-PLUS
	var globalEvent = uni.requireNativePlugin('globalEvent');
	const notify = uni.requireNativePlugin('Ba-Notify');
	//#endif
	var innerAudioContext = null;
	let client = null; //mqtt客户端
	let switches = 'admin_id'; //mqtt主题
	export default {
		onLaunch: function() {

			// let that = this;
			// const apiInfo = getCache('yf-APIS');
			// console.log('参数:', apiInfo);
			// if (apiInfo == '') {

			// } else {
			// 	that.ip = apiInfo.ip;
			// 	that.mqtt = apiInfo.mqtt;
			// 	that.port = apiInfo.port;
			// 	const token = getCache('yf-TOKEN');
			// 	if (token) {
			// 		uni.navigateTo({
			// 			url: '/pages/index/index'
			// 		})
			// 	} else {
			// 		uni.navigateTo({
			// 			url: '/pages/login/login'
			// 		})
			// 	}

			// }



			//that.autoplayMp();
			//that.startService();
			wx.getSystemInfo({
				success: (e) => {
					// #ifndef MP
					Vue.prototype.StatusBar = e.statusBarHeight;
					if (e.platform == "android") {
						Vue.prototype.CustomBar = e.statusBarHeight + 50;
					} else {
						Vue.prototype.CustomBar = e.statusBarHeight + 45;
					}
					// #endif
					// #ifdef MP-WEIXIN || MP-QQ
					Vue.prototype.StatusBar = e.statusBarHeight;
					let capsule = wx.getMenuButtonBoundingClientRect();
					if (capsule) {
						Vue.prototype.Custom = capsule;
						Vue.prototype.CustomBar =
							capsule.bottom + capsule.top - e.statusBarHeight;
					} else {
						Vue.prototype.CustomBar = e.statusBarHeight + 50;
					}
					// #endif

					// #ifdef MP-ALIPAY
					Vue.prototype.StatusBar = e.statusBarHeight;
					Vue.prototype.CustomBar = e.statusBarHeight + e.titleBarHeight;
					// #endif
				},
				fail(err) {
					console.log(err);
				},
			});



			// this.checkArguments();
			// // 重点是以下： 一定要监听后台恢复 ！一定要   
			// plus.globalEvent.addEventListener('newintent', (e) => {
			// 	this.checkArguments(); // 检测启动参数  
			// });

			// that.isNotifyEnabled();
			// that.connect();
			// setTimeout(() => {
			// 	uni.setKeepScreenOn({
			// 	    keepScreenOn: true
			// 	});
			// },20000)

			// setInterval(() => {
			// 	that.showknow()
			// }, 10000)
		},
		onShow: function() {
			let that = this;
			console.log("App Show");

			
			//this.subLocation();
			//this.test();


			//监听网络状态变化
			uni.onNetworkStatusChange(function(res) {
				that.getSystem(res);
				if (!res.isConnected) {
					uni.showToast({
						title: '检查网络是否连接',
						icon: "none"
					})
				}
			});
			if (getCache('network') == '') {
				this.getNetWork();

			}
		},
		onHide: function() {
			console.log("App Hide");
		},
		methods: {
			goPublish(){
			            //将vue项目引入至安卓代码中，安卓方法暴露在window中，vue中可以直接用window去调取方法。
			            window.android.callAndroidMethod('1','2')
			        },
			getNetWork() {
				let that = this;
				uni.getNetworkType({
					success: function(res) {
						//网络类型 wifi、2g、3g、4g、ethernet、unknown、none
						let messge = '';
						if (res.networkType != 'wifi' && res.networkType != 'none') {
							messge = '正在使用流量！';
							setCache('network', '流量' + res.networkType);
						} else if (res.networkType === 'wifi') {
							messge = '正在使用WIFI！';
							setCache('network', 'wifi');
						} else if (res.networkType === 'unknown') {
							messge = '未知！';
							setCache('network', '未知!');
						} else if (res.networkType == 'none') {
							messge = '网络异常，请稍后再试！';
							setCache('network', '无网络!');
						}
						uni.showToast({
							title: messge,
							icon: 'none',
							duration: 2000
						})

					}
				});
			},

			getSystem(res) {
				let that = this;
				// uni.getNetworkType({
				// 	success: function(res) {
				//网络类型 wifi、2g、3g、4g、ethernet、unknown、none
				let messge = '';
				if (res.networkType != 'wifi' && res.networkType != 'none') {
					messge = '正在使用流量！';
					setCache('network', '流量' + res.networkType);
				} else if (res.networkType === 'wifi') {
					messge = '正在使用WIFI！';
					setCache('network', 'wifi');
				} else if (res.networkType === 'unknown') {
					messge = '未知！';
					setCache('network', '未知!');
				} else if (res.networkType == 'none') {
					messge = '网络异常，请稍后再试！';
					setCache('network', '无网络!');
				}
				uni.showToast({
					title: messge,
					icon: 'none',
					duration: 2000
				})

				// 	}
				// });
			},
			//mqtt连接
			connect() {
				var that = this
				//h5的连接是 'ws://' + url。
				// #ifdef H5 
				client = this.$mqtt.connect('ws://' + MQTT_IP, MQTT_OPTIONS)
				// #endif 
				//app的连接是 'wx://' + url。
				//#ifdef MP-WEIXIN||APP-PLUS
				client = this.$mqtt.connect('wx://' + MQTT_IP, MQTT_OPTIONS)
				// #endif
				client.on('connect', function() {
					console.log('连接成功', client)
					//that.switches 这是订阅主题名称 和接口地址差不多，是他们定义的，直接拿过来用就行，订阅成功后，就可以接收这个的信息了
					client.subscribe(switches, function(err) {
						if (!err) {
							console.log('switches订阅成功')
						}
					});

				}).on('reconnect', function(error) {
					console.log('正在重连...', that.switches)
				}).on('error', function(error) {
					console.log('连接失败...', error)
				}).on('end', function() {
					console.log('连接断开')
				}).on('message', function(topic, message) {
					console.log('message');
					console.log(topic, message);
					that.showknow();
					// 统一接受信息。 topic 是订阅的主题名称，message是监听信息的接收和发送都能接收

				})
			},

			//是否打开通知权限
			isNotifyEnabled() {
				notify.isNotifyEnabled(
					(res) => {
						if (res.isNotifyEnabled) {
							uni.showToast({
								title: 'isNotifyEnabled：' + res.isNotifyEnabled ? true : false,
								icon: "none"
							})
						} else {
							this.goSetNotify();
						}

					});
			},
			goSetNotify() { //跳转到通知设置界面
				notify.goSetNotify();
			},
			clear() { //清空某类型消息
				notify.clear({
					'channelID': '0',
					'channelName': 'channel_0',
					'ID': 1,
				});
			},
			//发送告警通知
			showknow() {
				let that = this;
				uni.setKeepScreenOn({
					keepScreenOn: true
				});
				that.autoplayMp();
				notify.show({
						'channelID': '0',
						'channelName': '普通通知',
						'ID': 156,
						'notifyType': 0,
						'ticker': 'Ticker',
						'isVibrate': true,
						'title': '元沣智瞳',
						'content': '报警服务实时监听中...',
					},
					(res) => {
						console.log(res);
						setTimeout(() => {
							that.getVibrateLong();
						}, 2000)


					});

			},

			//长震动
			getVibrateLong() {
				// #ifdef APP-PLUS
				uni.vibrateLong({
					success: function() {
						console.log('success');
					}
				});
				// #endif
			},
			checkArguments() {
				var args = plus.runtime.arguments;
				if (args) {
					let args1 = JSON.parse(args);
					console.log('args1', args1);
					if (args1.notifyType == '0') {
						uni.navigateTo({
							url: '/pages/alarmDetail/alarmDetail?id=' + args1.BaNotifyID
						})
					}
					// 处理args参数，如直达到某新页面等
				}
			},

			//设置铃声
			autoplayMp() {
				// #ifdef APP-PLUS
				if (uni.getSystemInfoSync().platform == "ios") {
					plus.device.vibrate();
					plus.device.beep();

				} else if (uni.getSystemInfoSync().platform == "android") {
					// 震动
					plus.device.vibrate(2000);
					//声音
					let main = plus.android.runtimeMainActivity();
					let RingtoneManager = plus.android.importClass("android.media.RingtoneManager");
					let uri = RingtoneManager.getActualDefaultRingtoneUri(main, RingtoneManager.TYPE_NOTIFICATION);
					let MediaPlayer = plus.android.importClass("android.media.MediaPlayer");
					let player = MediaPlayer.create(main, uri);
					player.setLooping(false);
					player.prepare();
					player.start();
				}
				// #endif
			},
			startService() {

				var that = this;
				// #ifdef APP-PLUS
				const keepLiveService = uni.requireNativePlugin('yuange-YGKeepLiveServiceModule');
				keepLiveService.start({
					title: "我正在每2秒刷新一次日志",
					big_title: "带定时器的演示demo",
					content: "请不要关闭该服务，否则我无法刷新日志...",
					"delaysec": 2500,
					"isIgnoringBattery": false, //不开启电池优化
				}, result => {
					that.showknow()
					console.log(result)

				});
				//#endif
			},

			getLocation() {
				var that = this;
				// #ifdef APP-PLUS
				uni.getLocation({
					type: 'gcj02',
					geocode: true,
					highAccuracyExpireTime: 1000,
					success: function(res) {
						// that.longitude = res.longitude; // 经度
						// that.latitude = res.latitude; // 纬度
						// console.log('当前位置的经度：' + res.longitude);
						// console.log('当前位置的纬度：' + res.latitude);
						const obj = that.google_bd_encrypt(res.latitude, res.longitude);
						// console.log('百度坐标系：',obj);
						// console.log('当前地址：' + res.address.city);

						that.$api.getBanner().then(res => {
							if (res.code === 200) {
								uni.showToast({
									title: '获取数据成功',
									icon: "none",
									duration: 1000
								})
							}
						});
						// console.log(that.address)
						//that.address = res.address.district
					}
				});
				// #endif

			},
			google_bd_encrypt(gg_lat, gg_lon) {
				var x_pi = 3.14159265358979324 * 3000.0 / 180.0;
				var point = {};
				var x = gg_lon;
				var y = gg_lat;
				var z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
				var theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
				var bd_lon = z * Math.cos(theta) + 0.0065;
				var bd_lat = z * Math.sin(theta) + 0.006;
				point.lat = bd_lat;
				point.lon = bd_lon;
				return point;
			},

		},
	};
</script>

<style lang="scss">
	@import "@/uni_modules/uview-ui/index.scss";
	@import "@/static/font/icon.css";

	// @import "@/common/icon.css";
	// @import "@/colorui/main.css";
	// @import "@/colorui/icon.css";
	.uni-page-body {
		height: 100%
	}
</style>